package com.hxkcloud.patient.activitys;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

//import it.sauronsoftware.jave.AudioAttributes;
//import it.sauronsoftware.jave.Encoder;
//import it.sauronsoftware.jave.EncoderException;
//import it.sauronsoftware.jave.EncodingAttributes;
//import it.sauronsoftware.jave.InputFormatException;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.YjhApplication;
import com.hxkcloud.patient.beans.FileUploadBean;
import com.hxkcloud.patient.beans.InspectionReportBean;
import com.hxkcloud.patient.config.ApplicationConfig;
import com.hxkcloud.patient.popup.CalendarPopWindow;
import com.hxkcloud.patient.recorder.MediaManger;
import com.hxkcloud.patient.recorder.view.AudioRecorderButton;
import com.hxkcloud.patient.recorder.view.AudioRecorderLinearlayout;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BrightnessUtils;
import com.hxkcloud.patient.utils.ImageOptionUtils;
import com.hxkcloud.patient.utils.ImageUtil;
import com.hxkcloud.patient.utils.ImageVideoUtils;
import com.hxkcloud.patient.utils.StringUtil;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by william_sun on 2016-07-14.
 * Description:添加检查报告
 */
public class AddInspectionReportActivity extends BaseActivity implements View.OnClickListener, AudioRecorderLinearlayout.OnRecordingListener, TextWatcher {

    //title
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private TextView tv_del;

    private TextView tv_date;
    private EditText et_name;
    private EditText et_words;
    private ImageView iv1;
    private ImageView iv2;
    private ImageView iv3;
    private ImageView iv4;
    private ImageView iv5;
    private ImageView iv6;
    private ImageView iv7;
    private ImageView iv8;
    private ImageView iv9;
    private LinearLayout ll_voice;
    private TextView tv_voice;
    private Button bt_save;

    private PopupWindow popup_imgs;//选择图片、录音
    private Button bt_ptakep;
    private View view_pline1;
    private Button bt_pphoto;
    private View view_pline2;
    private Button bt_psound;
    private Button bt_pcancel;

    private PopupWindow popup_record;//录音popup
    private AudioRecorderButton bt_precord;

    private CalendarPopWindow popup_calendar;//选择录入数据

    private static final int TAKE_PHOTO_PICTURE = 1;
    private static final int SELECT_PICTURE = 3;

    private static final int DEL_PHOTO = 10;
    private static final int DEL_VOICE = 11;

    // 上传文件的内容
    private File cameraPath;
    private File cameraFile;
    private String cameraFileName;

    private ArrayList<String> imageUris;

    private String voicePath;

    private InspectionReportBean report;
    private boolean isEdit = false;//是否编辑

    //提交内容
    private String title = "";
    private String date = "";
    private String words = "";
    private long datel = 0;

    //两个按钮
    private PopupWindow popup_easynotice;
    private TextView tv_easynotice_title;
    private TextView tv_easynotice_cancel;
    private TextView tv_easynotice_func;

    private int funcType = 0;//弹出框操作，0删除，1不保存退出
    private boolean isModify = false;//记录是否修改内容，修改的话退出时提示是否不保存退出

    private boolean nameInput = false;//记录name输入框是否输入
    private boolean wordsInput = false;//记录words框是否输入

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addinspectionreport);

        if (this.getIntent().hasExtra("report")) {
            report = (InspectionReportBean) this.getIntent().getSerializableExtra("report");
        }

        initView();
        initPopup();
        initData();
    }

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_ADDMYINSPECTIONREPORT_SUCCESS:
                toastMsg(msg.obj.toString());
                Intent iBack = new Intent();
                iBack.putExtra("date", datel + "");
                setResult(RESULT_OK, iBack);
                finish();
                break;
            case MessageCode.NETWORKCODE_ADDMYINSPECTIONREPORT_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                } else {
                    toastMsg(getResources().getString(R.string.addinspectionreportfail));
                }
                break;
            case MessageCode.NETWORKCODE_FILEUPLOAD_SUCCESS:
                List<FileUploadBean> paths = (List<FileUploadBean>) msg.obj;
                String voiceFPath = "";
                List<String> imgsPath = new ArrayList<>();

                if (imageUris != null && imageUris.size() > 0) {
                    if (isEdit) {
//                        if (report.getImage() != null && report.getImage().size() > 0) {
//                            imgsPath.addAll(report.getImage());
//                        }
                        for (String uri : imageUris) {
                            if (uri.startsWith("http://")) {
                                imgsPath.add(uri);
                            }
                        }
                    }
                    for (FileUploadBean p : paths) {
                        imgsPath.add(p.getFilePath());
                    }
                } else if (voiceFPath != null) {
                    voiceFPath = paths.get(0).getFilePath();
                }

                if (isEdit) {
                    YiJiaHuNetWorkUtils.editMyInspectionReport(report.getInspectionReportId(), loginInfo.getPatientId(), datel + "", title, words, voiceFPath, imgsPath, handler);
                } else {
                    YiJiaHuNetWorkUtils.addMyInspectionReport(loginInfo.getUserId(), datel + "", title, words, voiceFPath, imgsPath, handler);
                }

                break;
            case MessageCode.NETWORKCODE_FILEUPLOAD_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                } else {
                    toastMsg(getResources().getString(R.string.fileuploadfail));
                }
                break;

            case MessageCode.NETWORKCODE_DOWNLOADVOICE_SUCCESS:
//                if (!MediaManger.isPlaying()) {
//                    MediaManger.playSound(ImageVideoUtils.getDataCacheDir(mContext) + "/voice", new MediaPlayer.OnCompletionListener() {
//                        @Override
//                        public void onCompletion(MediaPlayer mp) {
//                        }
//                    });
//                }

                ll_voice.setVisibility(View.VISIBLE);
                tv_voice.setText("");
                iv1.setVisibility(View.GONE);
                voicePath = ImageVideoUtils.getDataCacheDir(mContext) + "/voice.amr";
                break;
            case MessageCode.NETWORKCODE_DOWNLOADVOICE_FAILURE:
                iv1.setVisibility(View.VISIBLE);
                toastMsg(getResources().getString(R.string.voicedownloadfail));
                break;
            case MessageCode.NETWORKCODE_DELETEMYINSPECTIONREPORT_SUCCESS:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(getResources().getString(R.string.datadeletesuccess));
                }
                finish();
                break;
            case MessageCode.NETWORKCODE_DELETEMYINSPECTIONREPORT_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(getResources().getString(R.string.datadeletefail));
                }
                break;
        }
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);
        tv_del = (TextView) findViewById(R.id.tv_title_func);

        tv_date = (TextView) findViewById(R.id.tv_addreport_date);
        et_name = (EditText) findViewById(R.id.et_addreport_name);
        et_words = (EditText) findViewById(R.id.et_addreport_words);
        iv1 = (ImageView) findViewById(R.id.iv_addreport_img1);
        iv2 = (ImageView) findViewById(R.id.iv_addreport_img2);
        iv3 = (ImageView) findViewById(R.id.iv_addreport_img3);
        iv4 = (ImageView) findViewById(R.id.iv_addreport_img4);
        iv5 = (ImageView) findViewById(R.id.iv_addreport_img5);
        iv6 = (ImageView) findViewById(R.id.iv_addreport_img6);
        iv7 = (ImageView) findViewById(R.id.iv_addreport_img7);
        iv8 = (ImageView) findViewById(R.id.iv_addreport_img8);
        iv9 = (ImageView) findViewById(R.id.iv_addreport_img9);
        ll_voice = (LinearLayout) findViewById(R.id.ll_addreport_voice);
        tv_voice = (TextView) findViewById(R.id.tv_addreport_voice);
        bt_save = (Button) findViewById(R.id.bt_addreport_save);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        if (report != null) {
            tv_title.setText(getResources().getText(R.string.editreport));
        } else {
            tv_title.setText(getResources().getText(R.string.addreport));
        }
        iv_back.setOnClickListener(this);
        tv_del.setVisibility(View.VISIBLE);
        tv_del.setText(R.string.delete);
        tv_del.setOnClickListener(this);
        if (report != null) {
            tv_del.setVisibility(View.VISIBLE);
        } else {
            tv_del.setVisibility(View.INVISIBLE);
        }

        iv1.setOnClickListener(this);
        iv2.setOnClickListener(this);
        iv3.setOnClickListener(this);
        iv4.setOnClickListener(this);
        iv5.setOnClickListener(this);
        iv6.setOnClickListener(this);
        iv7.setOnClickListener(this);
        iv8.setOnClickListener(this);
        iv9.setOnClickListener(this);

        LinearLayout.LayoutParams lp_iv = new LinearLayout.LayoutParams((screenWidth - ImageUtil.dip2px(30, mContext)) / 3, screenWidth / 3);
        LinearLayout.LayoutParams lp_iv1 = new LinearLayout.LayoutParams((screenWidth - ImageUtil.dip2px(30, mContext)) / 3, screenWidth / 3);
        lp_iv1.leftMargin = ImageUtil.dip2px(5, mContext);
        iv1.setLayoutParams(lp_iv);
        iv2.setLayoutParams(lp_iv1);
        iv3.setLayoutParams(lp_iv1);
        iv4.setLayoutParams(lp_iv);
        iv5.setLayoutParams(lp_iv1);
        iv6.setLayoutParams(lp_iv1);
        iv7.setLayoutParams(lp_iv);
        iv8.setLayoutParams(lp_iv1);
        iv9.setLayoutParams(lp_iv1);

        ll_voice.setVisibility(View.GONE);
        ll_voice.setOnClickListener(this);

        tv_date.setOnClickListener(this);
        bt_save.setOnClickListener(this);

        et_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (StringUtil.isEmpty(s.toString())) {
                    nameInput = false;
                    bt_save.setBackgroundResource(R.drawable.bt_grey);
                    bt_save.setEnabled(false);
                } else {
                    nameInput = true;
                    if (wordsInput || imageUris.size() > 0 || !TextUtils.isEmpty(voicePath)) {
                        bt_save.setBackgroundResource(R.drawable.bt_green);
                        bt_save.setEnabled(true);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_words.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (StringUtil.isEmpty(s.toString())) {
                    wordsInput = false;
                    if (imageUris.size() > 0 || !TextUtils.isEmpty(voicePath)) {
                        bt_save.setBackgroundResource(R.drawable.bt_green);
                        bt_save.setEnabled(true);
                    } else {
                        bt_save.setBackgroundResource(R.drawable.bt_grey);
                        bt_save.setEnabled(false);
                    }
                } else {
                    wordsInput = true;
                    if (nameInput) {
                        bt_save.setBackgroundResource(R.drawable.bt_green);
                        bt_save.setEnabled(true);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void initPopup() {
        popup_imgs = new PopupWindow(this);
        View viewImgs = LayoutInflater.from(mContext).inflate(R.layout.popup_addreport, null);
        popup_imgs.setContentView(viewImgs);

        popup_imgs.setWidth(screenWidth);
        popup_imgs.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_imgs.setFocusable(true);
        popup_imgs.setTouchable(true);
        popup_imgs.setOutsideTouchable(true);
        popup_imgs.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup_imgs.setAnimationStyle(R.style.popupwindow_anim_default);

        bt_ptakep = (Button) viewImgs.findViewById(R.id.bt_addreport_takep);
        view_pline1 = viewImgs.findViewById(R.id.view_addreport_line1);
        bt_pphoto = (Button) viewImgs.findViewById(R.id.bt_addreport_photo);
        view_pline2 = viewImgs.findViewById(R.id.view_addreport_line2);
        bt_psound = (Button) viewImgs.findViewById(R.id.bt_addreport_sound);
        bt_pcancel = (Button) viewImgs.findViewById(R.id.bt_addreport_cancel);

        bt_ptakep.setOnClickListener(this);
        bt_pphoto.setOnClickListener(this);
        bt_psound.setOnClickListener(this);
        bt_pcancel.setOnClickListener(this);

//        bt_psound.setOnRecordingListener(this);

        popup_imgs.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(AddInspectionReportActivity.this);
            }
        });

        popup_record = new PopupWindow(this);
        View viewRecord = LayoutInflater.from(mContext).inflate(R.layout.popup_record, null);
        popup_record.setContentView(viewRecord);
        popup_record.setWidth(screenWidth);
        popup_record.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_record.setFocusable(true);
        popup_record.setTouchable(true);
        popup_record.setOutsideTouchable(true);
        popup_record.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup_record.setAnimationStyle(R.style.popupwindow_anim_default);

        bt_precord = (AudioRecorderButton) viewRecord.findViewById(R.id.bt_record_sound);
        bt_precord.setOnRecordingListener(this);
        popup_record.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(AddInspectionReportActivity.this);
            }
        });

        popup_calendar = new CalendarPopWindow(this);
        popup_calendar.setCalendarListener(new CalendarPopWindow.CalendarListener() {
            @Override
            public void setCalendar(String calendar) {
                tv_date.setText(calendar);//new SimpleDateFormat("yyyy-MM-dd")
                isModify = true;
            }
        });

        //easynotice
        popup_easynotice = new PopupWindow(this);
        View viewNotice = LayoutInflater.from(this).inflate(R.layout.popup_easynotice, null);
        popup_easynotice.setContentView(viewNotice);

        popup_easynotice.setWidth((int) (screenWidth * 0.7));
        popup_easynotice.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_easynotice.setFocusable(true);
        popup_easynotice.setTouchable(true);
        popup_easynotice.setOutsideTouchable(true);
        popup_easynotice.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup_easynotice.setAnimationStyle(R.style.popupwindow_anim_alpha);

        tv_easynotice_title = (TextView) viewNotice.findViewById(R.id.tv_easynotice_title);
        tv_easynotice_cancel = (TextView) viewNotice.findViewById(R.id.tv_easynotice_cancel);
        tv_easynotice_func = (TextView) viewNotice.findViewById(R.id.tv_easynotice_func);

        tv_easynotice_cancel.setOnClickListener(this);
        tv_easynotice_func.setOnClickListener(this);

        popup_easynotice.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(AddInspectionReportActivity.this);
                funcType = 0;
            }
        });
    }

    //0全部 1图片 2录音
    private void showPopup(int type) {
        closeInputMethodManager();
        bt_psound.setText(R.string.soundrecord);
        if (type == 0) {
            bt_ptakep.setVisibility(View.VISIBLE);
            view_pline1.setVisibility(View.VISIBLE);
            bt_pphoto.setVisibility(View.VISIBLE);
            view_pline2.setVisibility(View.VISIBLE);
            bt_psound.setVisibility(View.VISIBLE);
        } else if (type == 1) {
            bt_ptakep.setVisibility(View.VISIBLE);
            view_pline1.setVisibility(View.VISIBLE);
            bt_pphoto.setVisibility(View.VISIBLE);
            view_pline2.setVisibility(View.GONE);
            bt_psound.setVisibility(View.GONE);
        } else if (type == 2) {
            bt_ptakep.setVisibility(View.GONE);
            view_pline1.setVisibility(View.GONE);
            bt_pphoto.setVisibility(View.GONE);
            view_pline2.setVisibility(View.GONE);
            bt_psound.setVisibility(View.VISIBLE);
        }
        popup_imgs.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
        BrightnessUtils.lightOff(AddInspectionReportActivity.this);
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {
        et_name.addTextChangedListener(this);
        et_words.addTextChangedListener(this);

        cameraPath = new File(ApplicationConfig.PicAndVideoUrl);
        if (!cameraPath.exists()) {
            cameraPath.mkdirs();
        }

        imageUris = new ArrayList<>();

        if (report != null) {
            isEdit = true;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String date = sdf.format(new Date(Long.valueOf(report.getDate())));
            tv_date.setText(date);
            et_name.setText(report.getTitle());
            et_words.setText(report.getWords());


            if (report.getImage() != null && report.getImage().size() > 0) {
                imageUris.addAll(report.getImage());
                switch (imageUris.size()) {
                    case 9:
                        iv9.setVisibility(View.VISIBLE);
                        imageLoader.displayImage(imageUris.get(8), iv9, ImageOptionUtils.getInstance().getSimplePicOptions());
                    case 8:
                        iv8.setVisibility(View.VISIBLE);
                        imageLoader.displayImage(imageUris.get(7), iv8, ImageOptionUtils.getInstance().getSimplePicOptions());
                    case 7:
                        iv7.setVisibility(View.VISIBLE);
                        imageLoader.displayImage(imageUris.get(6), iv7, ImageOptionUtils.getInstance().getSimplePicOptions());
                    case 6:
                        iv6.setVisibility(View.VISIBLE);
                        imageLoader.displayImage(imageUris.get(5), iv6, ImageOptionUtils.getInstance().getSimplePicOptions());
                    case 5:
                        iv5.setVisibility(View.VISIBLE);
                        imageLoader.displayImage(imageUris.get(4), iv5, ImageOptionUtils.getInstance().getSimplePicOptions());
                    case 4:
                        iv4.setVisibility(View.VISIBLE);
                        imageLoader.displayImage(imageUris.get(3), iv4, ImageOptionUtils.getInstance().getSimplePicOptions());
                    case 3:
                        iv3.setVisibility(View.VISIBLE);
                        imageLoader.displayImage(imageUris.get(2), iv3, ImageOptionUtils.getInstance().getSimplePicOptions());
                    case 2:
                        iv2.setVisibility(View.VISIBLE);
                        imageLoader.displayImage(imageUris.get(1), iv2, ImageOptionUtils.getInstance().getSimplePicOptions());
                    case 1:
                        iv1.setVisibility(View.VISIBLE);
                        imageLoader.displayImage(imageUris.get(0), iv1, ImageOptionUtils.getInstance().getSimplePicOptions());
                        break;
                }
                if (getIndexIv(imageUris.size()) != null) {
                    getIndexIv(imageUris.size()).setVisibility(View.VISIBLE);
                }
            } else if (!TextUtils.isEmpty(report.getVoice())) {
                String url = report.getVoice().replace(".amr.mp3", ".amr");
                YiJiaHuNetWorkUtils.downloadFile(url, mContext, handler);

                ll_voice.setVisibility(View.VISIBLE);
                tv_voice.setText("");
                iv1.setVisibility(View.GONE);
                voicePath = "";//ImageVideoUtils.getDataCacheDir(mContext) + "/voice.amr";

//                ll_voice.setVisibility(View.VISIBLE);
//                tv_voice.setText("");
//                iv1.setVisibility(View.GONE);
//                voicePath = report.getVoice();yyyy-MM-dd

            }

            nameInput = true;
            wordsInput = true;
            bt_save.setBackgroundResource(R.drawable.bt_green);
            bt_save.setEnabled(true);
        } else {
            Calendar cal = Calendar.getInstance();
            String date = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH);
            tv_date.setText(date);

            nameInput = false;
            wordsInput = false;
            bt_save.setBackgroundResource(R.drawable.bt_grey);
            bt_save.setEnabled(false);
        }


    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
            if (isModify) {
                funcType = 1;
                tv_easynotice_title.setText(getResources().getString(R.string.modifynotsave_surequit));
                tv_easynotice_cancel.setText(getResources().getString(R.string.cancel));
                tv_easynotice_func.setText(getResources().getString(R.string.quit));
                popup_easynotice.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
                BrightnessUtils.lightOff(this);
            } else {
                finish();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                if (isModify) {
                    funcType = 1;
                    tv_easynotice_title.setText(getResources().getString(R.string.modifynotsave_surequit));
                    tv_easynotice_cancel.setText(getResources().getString(R.string.cancel));
                    tv_easynotice_func.setText(getResources().getString(R.string.quit));
                    popup_easynotice.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
                    BrightnessUtils.lightOff(this);
                } else {
                    finish();
                }
                break;
            case R.id.tv_title_func:
                funcType = 0;
                tv_easynotice_title.setText(getResources().getString(R.string.suredeletereport));
                tv_easynotice_cancel.setText(getResources().getString(R.string.cancel));
                tv_easynotice_func.setText(getResources().getString(R.string.delete));
                popup_easynotice.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
                BrightnessUtils.lightOff(this);
                break;
            case R.id.bt_addreport_takep:
                popup_imgs.dismiss();
                Intent iTakep = new Intent();
                iTakep.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                cameraFileName = System.currentTimeMillis() + ".jpg";
                cameraFile = new File(cameraPath, cameraFileName);
                if (cameraFile.exists()) {
                    cameraFile.delete();
                }
                iTakep.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(cameraFile));
                startActivityForResult(iTakep,
                        TAKE_PHOTO_PICTURE);
                break;
            case R.id.bt_addreport_photo:
                popup_imgs.dismiss();
                Intent iPhoto = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                iPhoto.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(iPhoto,
                        SELECT_PICTURE);
                break;
            case R.id.bt_addreport_sound:
                popup_imgs.dismiss();
                popup_record.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
                BrightnessUtils.lightOff(AddInspectionReportActivity.this);
                break;
            case R.id.bt_addreport_cancel:
                popup_imgs.dismiss();
                break;
            case R.id.iv_addreport_img1:
                if (imageUris.size() == 0) {
                    showPopup(0);
                } else {
                    seePhotos(0);
                }
                break;
            case R.id.iv_addreport_img2:
                if (imageUris.size() == 1) {
                    showPopup(1);
                } else {
                    seePhotos(1);
                }
                break;
            case R.id.iv_addreport_img3:
                if (imageUris.size() == 2) {
                    showPopup(1);
                } else {
                    seePhotos(2);
                }
                break;
            case R.id.iv_addreport_img4:
                if (imageUris.size() == 3) {
                    showPopup(1);
                } else {
                    seePhotos(3);
                }
                break;
            case R.id.iv_addreport_img5:
                if (imageUris.size() == 4) {
                    showPopup(1);
                } else {
                    seePhotos(4);
                }
                break;
            case R.id.iv_addreport_img6:
                if (imageUris.size() == 5) {
                    showPopup(1);
                } else {
                    seePhotos(5);
                }
                break;
            case R.id.iv_addreport_img7:
                if (imageUris.size() == 6) {
                    showPopup(1);
                } else {
                    seePhotos(6);
                }
                break;
            case R.id.iv_addreport_img8:
                if (imageUris.size() == 7) {
                    showPopup(1);
                } else {
                    seePhotos(7);
                }
                break;
            case R.id.iv_addreport_img9:
                if (imageUris.size() == 8) {
                    showPopup(1);
                } else {
                    seePhotos(8);
                }
                break;
            case R.id.ll_addreport_voice:
                Intent iRecorder = new Intent(mContext, RecorderActivity.class);
                iRecorder.putExtra("path", voicePath);
                startActivityForResult(iRecorder, DEL_VOICE);

                break;
            case R.id.tv_addreport_date:
                closeInputMethodManager();
                popup_calendar.showBottom(ll_title);
                break;
            case R.id.bt_addreport_save:
                title = et_name.getText().toString().trim();
                date = tv_date.getText().toString().trim();
                words = et_words.getText().toString().trim();
                datel = 0;
                if (TextUtils.isEmpty(title) || TextUtils.isEmpty(date) || (TextUtils.isEmpty(words)) && imageUris.size() == 0 && TextUtils.isEmpty(voicePath)) {
                    toastMsg(R.string.pleaseinputwholecontent);
                    return;
                }
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Date d = sdf.parse(date);
                    datel = d.getTime();
                } catch (ParseException e) {

                }
//                List<String> imgs = new ArrayList<>();
//                if (isModify) {
//                    YiJiaHuNetWorkUtils.editMyInspectionReport(report.getInspectionReportId(), loginInfo.getUserId(), datel + "", title, words, "", imgs, handler);
//                } else {
//                    YiJiaHuNetWorkUtils.addMyInspectionReport(loginInfo.getUserId(), datel + "", title, words, "", imgs, handler);
//                }
                loading();
                if (imageUris != null && imageUris.size() > 0) {
                    if (isEdit && report.getImage().size() > 0) {
//                        if (imageUris.size() > report.getImage().size()) {
//                            List<File> images = new ArrayList<>();
//                            for (int i = report.getImage().size(); i < imageUris.size(); i++) {
//                                images.add(new File(imageUris.get(i)));
//                            }
//                            YiJiaHuNetWorkUtils.FileUpload(images, YjhApplication.file_image, handler);
//                        } else {
//                            YiJiaHuNetWorkUtils.editMyInspectionReport(report.getInspectionReportId(), loginInfo.getPatientId(), datel + "", title, words, report.getVoice(), report.getImage(), handler);
//                        }
                        List<File> images = new ArrayList<>();//记录新加的图片
                        for (String imageUri : imageUris) {
                            if (!imageUri.startsWith("http://")) {
                                images.add(new File(imageUri));
                            }
                        }
                        if (images.size() > 0) {
                            YiJiaHuNetWorkUtils.FileUpload(images, YjhApplication.file_image, handler);
                        } else {
                            List<String> oldImages = new ArrayList<>();
                            for (String imageUri : imageUris) {
                                oldImages.add(imageUri);
                            }
                            YiJiaHuNetWorkUtils.editMyInspectionReport(report.getInspectionReportId(), loginInfo.getPatientId(), datel + "", title, words, report.getVoice(), oldImages, handler);
                        }
                    } else {
                        List<File> images = new ArrayList<>();
                        for (String img : imageUris) {
                            images.add(new File(img));
                        }
                        YiJiaHuNetWorkUtils.FileUpload(images, YjhApplication.file_image, handler);
                    }
                } else if (!TextUtils.isEmpty(voicePath)) {
                    List<File> voices = new ArrayList<>();
                    voices.add(new File(voicePath));
                    YiJiaHuNetWorkUtils.FileUpload(voices, YjhApplication.file_media, handler);
                } else {
                    if (isEdit) {
                        YiJiaHuNetWorkUtils.editMyInspectionReport(report.getInspectionReportId(), loginInfo.getPatientId(), datel + "", title, words, "", null, handler);
                    } else {
                        YiJiaHuNetWorkUtils.addMyInspectionReport(loginInfo.getUserId(), datel + "", title, words, "", null, handler);
                    }
                }

                break;
            case R.id.tv_easynotice_cancel:
                popup_easynotice.dismiss();
                break;
            case R.id.tv_easynotice_func:
                if (funcType == 0) {//0删除
                    if (isEdit) {
                        popup_easynotice.dismiss();
                        loading();
                        YiJiaHuNetWorkUtils.deleteMyInspectionReport(report.getInspectionReportId(), loginInfo.getPatientId(), handler);
                    }
                }
                if (funcType == 1) {//1不保存退出
                    popup_easynotice.dismiss();
                    finish();
                }
                break;
        }
    }

    private void seePhotos(int index) {
        Intent iPhotos = new Intent(mContext, PhotosActivity.class);
        iPhotos.putExtra("index", index);
        iPhotos.putStringArrayListExtra("urls", imageUris);
        startActivityForResult(iPhotos, DEL_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case TAKE_PHOTO_PICTURE:
                    if (cameraFile != null) {
//                        ImageVideoUtils.compressPicture(cameraFile, cameraFile);
//                        Bitmap mBitmap = BitmapFactory.decodeFile(cameraFile.getAbsolutePath());
//                        getCurIv().setImageBitmap(mBitmap);

                        String u = cameraFile.getAbsolutePath();
                        imageLoader.displayImage("file://" + u, getCurIv(), ImageOptionUtils.getInstance().getSimplePicOptions());

                        if (getNextIv() != null) {
                            getNextIv().setVisibility(View.VISIBLE);
                        }

                        imageUris.add(u);
                        isModify = true;

                        if (nameInput) {
                            bt_save.setBackgroundResource(R.drawable.bt_green);
                            bt_save.setEnabled(true);
                        }

                    }
                    break;
                case SELECT_PICTURE:
                    if (data.getData() != null) {
                        Uri uri = data.getData();
                        if (uri != null) {
                            String u = ImageVideoUtils.getImagePathForUri(uri, mContext);
//                            cameraFile = new File(u);
//                            ImageVideoUtils.compressPicture(cameraFile, cameraFile);
//                            Bitmap mBitmap = BitmapFactory.decodeFile(cameraFile.getAbsolutePath());
//                            getCurIv().setImageBitmap(mBitmap);
                            imageLoader.displayImage("file://" + u, getCurIv(), ImageOptionUtils.getInstance().getSimplePicOptions());
                            if (getNextIv() != null) {
                                getNextIv().setVisibility(View.VISIBLE);
                            }

                            imageUris.add(u);
                            isModify = true;

                            if (nameInput) {
                                bt_save.setBackgroundResource(R.drawable.bt_green);
                                bt_save.setEnabled(true);
                            }

                        }
                    }
                    break;
                case DEL_PHOTO:
                    if (data.hasExtra("index")) {
                        int del = data.getIntExtra("index", 0);
                        if (del < imageUris.size()) {
                            if (del == imageUris.size() - 1) {
                                getLastIv().setImageResource(R.drawable.report_add);
                                if (getCurIv() != null) {
                                    getCurIv().setVisibility(View.GONE);
                                }
                            } else {
                                for (int i = del; i < imageUris.size() - 1; i++) {
                                    if (imageUris.get(i + 1).startsWith("http://")) {
                                        imageLoader.displayImage(imageUris.get(i + 1), getIndexIv(i), ImageOptionUtils.getInstance().getSimplePicOptions());
                                    } else {
                                        cameraFile = new File(imageUris.get(i + 1));
                                        Bitmap mBitmap = BitmapFactory.decodeFile(cameraFile.getAbsolutePath());
                                        getIndexIv(i).setImageBitmap(mBitmap);
                                    }
                                }
                                getLastIv().setImageResource(R.drawable.report_add);
                                if (getCurIv() != null) {
                                    getCurIv().setVisibility(View.GONE);
                                }
                            }

                            imageUris.remove(del);
                            isModify = true;

                            if (imageUris.size() == 0) {
                                if (!wordsInput && TextUtils.isEmpty(voicePath)) {
                                    bt_save.setBackgroundResource(R.drawable.bt_grey);
                                    bt_save.setEnabled(false);
                                }
                            }
                        }
                    }
                    break;
                case DEL_VOICE:
                    delSound();
                    isModify = true;

                    if (imageUris.size() == 0 && !wordsInput) {
                        bt_save.setBackgroundResource(R.drawable.bt_grey);
                        bt_save.setEnabled(false);
                    }
                    break;
            }
        }
    }

    private ImageView getIndexIv(int index) {
        ImageView iv = null;
        switch (index) {
            case 0:
                iv = iv1;
                break;
            case 1:
                iv = iv2;
                break;
            case 2:
                iv = iv3;
                break;
            case 3:
                iv = iv4;
                break;
            case 4:
                iv = iv5;
                break;
            case 5:
                iv = iv6;
                break;
            case 6:
                iv = iv7;
                break;
            case 7:
                iv = iv8;
                break;
            case 8:
                iv = iv9;
                break;
        }
        return iv;
    }

    private ImageView getCurIv() {
        ImageView iv = null;
        if (imageUris != null) {
            switch (imageUris.size()) {
                case 0:
                    iv = iv1;
                    break;
                case 1:
                    iv = iv2;
                    break;
                case 2:
                    iv = iv3;
                    break;
                case 3:
                    iv = iv4;
                    break;
                case 4:
                    iv = iv5;
                    break;
                case 5:
                    iv = iv6;
                    break;
                case 6:
                    iv = iv7;
                    break;
                case 7:
                    iv = iv8;
                    break;
                case 8:
                    iv = iv9;
                    break;
                default:
                    iv = null;
                    break;
            }
        } else {
            iv = null;
        }
        return iv;
    }

    private ImageView getLastIv() {
        ImageView iv = null;
        if (imageUris != null) {
            switch (imageUris.size()) {
                case 0:

                    break;
                case 1:
                    iv = iv1;
                    break;
                case 2:
                    iv = iv2;
                    break;
                case 3:
                    iv = iv3;
                    break;
                case 4:
                    iv = iv4;
                    break;
                case 5:
                    iv = iv5;
                    break;
                case 6:
                    iv = iv6;
                    break;
                case 7:
                    iv = iv7;
                    break;
                case 8:
                    iv = iv8;
                    break;
                case 9:
                    iv = iv9;
                    break;
                default:
                    iv = null;
                    break;
            }
        } else {
            iv = null;
        }
        return iv;
    }

    private ImageView getNextIv() {
        ImageView iv = null;
        if (imageUris != null) {
            switch (imageUris.size()) {
                case 0:
                    iv = iv2;
                    break;
                case 1:
                    iv = iv3;
                    break;
                case 2:
                    iv = iv4;
                    break;
                case 3:
                    iv = iv5;
                    break;
                case 4:
                    iv = iv6;
                    break;
                case 5:
                    iv = iv7;
                    break;
                case 6:
                    iv = iv8;
                    break;
                case 7:
                    iv = iv9;
                    break;
                case 8:
                    iv = null;
                    break;
                default:
                    iv = null;
                    break;
            }
        } else {
            iv = null;
        }
        return iv;
    }

    @Override
    public void onFinish(float seconds, String filePath) {
        ll_voice.setVisibility(View.VISIBLE);
        tv_voice.setText("\"" + Math.round(seconds));
        iv1.setVisibility(View.GONE);
        voicePath = filePath;
//        String path1 = voicePath.replace(".amr", ".mp3");
//        File file1 = new File(path1);
//        if (!file1.exists()) {
//            file1.mkdir();
//        }
//        amrTpMps(voicePath, path1);
//        voicePath = path1;

        popup_record.dismiss();
        isModify = true;

        if (nameInput) {
            bt_save.setBackgroundResource(R.drawable.bt_green);
            bt_save.setEnabled(true);
        }
    }
//
//    private void amrTpMps(String sourcePath, String targetPath) {
//        File source = new File(sourcePath);
//        File target = new File(targetPath);
//        AudioAttributes audio = new AudioAttributes();
//        Encoder encoder = new Encoder();
//
//        audio.setCodec("libmp3lame");
//        EncodingAttributes attrs = new EncodingAttributes();
//        attrs.setFormat("mp3");
//        attrs.setAudioAttributes(audio);
//
//        try {
//            encoder.encode(source, target, attrs);
//        } catch (IllegalArgumentException e) {
//            e.printStackTrace();
//        } catch (InputFormatException e) {
//            e.printStackTrace();
//        } catch (EncoderException e) {
//            e.printStackTrace();
//        }
//    }

    @Override
    public void stateNormal() {
        bt_psound.setText(getString(R.string.str_recorder_normal));
    }

    @Override
    public void stateRecording() {
        bt_psound.setText(getString(R.string.str_recorder_recording));
    }

    @Override
    public void stateWantToCancel() {
        bt_psound.setText(getString(R.string.str_recorder_want_cancel));
    }

    @Override
    public void click(String filePath) {
        //play
//        bt_psound.setBackgroundResource(R.mipmap.adj);
//        if (!MediaManger.isPlaying()) {
//            //播放动画
//            iv_recorder_anim.setBackgroundResource(R.drawable.paly_anim);
//            AnimationDrawable anim = (AnimationDrawable) iv_recorder_anim.getBackground();
//            anim.start();
//            //播放音频
//            audio_scoop.setBackgroundResource(R.drawable.btn_recording);
//            MediaManger.playSound(filePath, new MediaPlayer.OnCompletionListener() {
//                @Override
//                public void onCompletion(MediaPlayer mp) {
//                    iv_recorder_anim.setBackgroundResource(R.mipmap.adj);
//                    audio_scoop.setBackgroundResource(R.drawable.btn_recorder_normal);
//                }
//            });
//        } else {
//            MediaManger.release();
//            audio_scoop.setBackgroundResource(R.drawable.btn_recorder_normal);
//        }
    }

    public void delSound() {
        if (!TextUtils.isEmpty(voicePath)) {
            deleteAudio();
            ll_voice.setVisibility(View.GONE);
            iv1.setVisibility(View.VISIBLE);
            iv1.setImageResource(R.drawable.report_add);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        deleteAudio();
    }

    public void deleteAudio() {
//        if (!TextUtils.isEmpty(bt_psound.getmAudioManager().getCurrentFilePath())) {
//            MediaManger.release();
//            File file = new File(bt_psound.getmAudioManager().getCurrentFilePath());
//            if (file.exists())
//                file.delete();
//            bt_psound.getmAudioManager().setCurrentFilePath("");
//            voicePath = "";
//        }
        if (!TextUtils.isEmpty(voicePath)) {
            MediaManger.release();
            File file = new File(voicePath);
            if (file.exists())
                file.delete();
            bt_precord.getmAudioManager().setCurrentFilePath("");
            voicePath = "";
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (isEdit) {
            if (s.toString().equals(report.getTitle()) || s.toString().equals(report.getWords())) {

            } else {
                isModify = true;
            }
        } else {
            isModify = true;
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
